package com.example.lenovo.asia5b.my.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.PaintDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.lenovo.asia5b.my.adapter.AccountDetAdapter;
import com.example.lenovo.asia5b.my.adapter.ListTimeAdapter;
import com.example.lenovo.asia5b.my.adapter.SecondClassAdapter;
import com.example.lenovo.asia5b.my.bean.AccountDetBean;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.ui.PullToRefreshLayout;
import com.example.lenovo.asia5b.util.DensityUtil;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;

import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;
import static com.wushi.lenovo.asia5b.R.id.public_btn_left;
import static com.wushi.lenovo.asia5b.R.id.public_txt_righe;


/**
 * Created by lenovo on 2017/6/22.
 */

public class AccountDetailsActivity extends BaseActivity implements ICallBack, PullToRefreshLayout.OnRefreshListener {
    private  ListView lv_record_top_up;
    private AccountDetAdapter adapter;
    private ListTimeAdapter lv_adapter;
    private LoadingDalog loadingDalog;
    private int page  = 1;
    private int countPage = 0;
    private PullToRefreshLayout pullToRefreshLayout;
    private  List<AccountDetBean> lists = null;
    private PopupWindow pop;
    private Dialog showAccountDialog;
    private ListView mHomePopListviewLeft,mHomePopListviewRight;
    private Context mContext;
    private List<String> mFirstList,mSecondList;

    private PopupWindow mPopupWindow;

    private String str_time = "0",str_billtype = "-1";

    private TextView txt_account_sure;
    private ImageView txt_btn_left;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_details);
        initView();
        userAccountData();
        initPopup();

    }
    public void initView() {
        loadingDalog = new LoadingDalog(this);
        loadingDalog.show();

        F.id(R.id.btn_change_information).clicked(this);
        F.id(R.id.public_title_name).text(getResources().getString(R.string.account_details));
        pullToRefreshLayout = ((PullToRefreshLayout)findViewById(R.id.refresh_view));
        pullToRefreshLayout.setOnRefreshListener(this);
        F.id(public_btn_left).clicked(this);
        F.id(public_txt_righe).visibility(View.VISIBLE);
        F.id(public_txt_righe).text(getResources().getString(R.string.sx));
        F.id(public_txt_righe).clicked(this);
        lv_record_top_up = (ListView)findViewById(R.id.lv_record_top_up);
        adapter = new AccountDetAdapter(this);
        lv_record_top_up.setAdapter(adapter);
        lv_record_top_up.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(AccountDetailsActivity.this,AccountDetailsDetActivity.class);
                intent.putExtra("id",adapter.getLists().get(i));
                startActivity(intent);
            }
        });
        lv_record_top_up.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // 当不滚动时
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (view.getLastVisiblePosition() == view.getCount() - 1) {
                        if (page < countPage) {
                            page += 1;
                            notifData();
                        } else {
                            TextView load_tv = (TextView)findViewById(R.id.load_tv);
                            load_tv.setText(getResources().getString(R.string.no_more_data));
                            load_tv.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        });
    }

    /**
     * 获取账户明细接口
     */
    public void userAccountData() {
        try {
            page = 1;
            loadingDalog.show();
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.USER_ACCOUNT;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"page"+page,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr.toString()));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("page",""+page);
            parmaMap.put("billtype",str_billtype);
            parmaMap.put("filter_time",str_time);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 0);
        }catch (Exception e) {

        }
    }

    private void notifData(){
        try {
//            adapter.clear();
            loadingDalog.show();
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.USER_ACCOUNT;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"page"+page,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr.toString()));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("page",""+page);
            parmaMap.put("billtype",str_billtype);
            parmaMap.put("filter_time",str_time);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 0);
        }catch (Exception e) {

        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case public_btn_left:
                finish();
                break;
            case public_txt_righe:
                if (mPopupWindow.isShowing()){
                    F.id(public_txt_righe).text(getResources().getString(R.string.sx));
                }else{
                    F.id(public_txt_righe).text(getResources().getString(R.string.qd));
                    showPop();
                }
                break;
            case R.id.txt_account_sure:

                F.id(public_txt_righe).text(getResources().getString(R.string.sx));
                mPopupWindow.dismiss();
                userAccountData();

                break;

            case R.id.txt_btn_left:
                finish();
                break;

            default:
                break;
        }
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json =  (JSONObject)result;
                        int state = (int)json.getInt("State");
                        if (state == 0) {
                            JSONObject paging = json.getJSONObject("paging");
                            if (null!=paging.getString("page") && "1".equals(paging.getString("page"))) {
                                if (lists != null && lists.size() > 0){
                                    adapter.clear();
                                }
                                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                                initPaging(paging);
                                JSONArray account = json.getJSONArray("account");
                                lists = Logic.getListToBean(account,new AccountDetBean());
                                adapter.setLists(lists);
                                adapter.notifyDataSetChanged();

                            } else if(null!=paging.getString("page") && !"1".equals(paging.getString("page"))){
                                pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                                JSONArray account = (JSONArray) json.get("account");
                                if (null != account && account.length() > 0) {
                                    List<AccountDetBean> listBean  =  Logic.getListToBean(account,new AccountDetBean());
                                    for (int i = 0; i < listBean.size(); i++) {
                                        lists .add(listBean.get(i));
                                    }
                                    adapter .setLists(lists);
                                    adapter .notifyDataSetChanged();
                                } else {
                                    page = page - 1;
                                }

                            }

                        }  else if(state == 1){
                            U.Toast(AccountDetailsActivity.this,getResources().getString(R.string.qmsb)
                            );
                        }else if(state == 2){
                            U.Toast(AccountDetailsActivity.this,getResources().getString(R.string.cscw)
                            );
                        }else if(state == 3){
                            U.Toast(AccountDetailsActivity.this,getResources().getString(R.string.wdl)
                            );
                        }else if(state == 4){
                            U.Toast(AccountDetailsActivity.this,getResources().getString(R.string.mysj)
                            );
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
            }
        }
    };

    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
        }

    /**
     * 向下刷新
     */
    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        userAccountData();
    }

    /**
     * 向上加载
     */
    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
    }

    public void initPaging(JSONObject json) throws JSONException {
        String pageSizeString = json.getString("count");
        String countPageString = json.getString("countpage");
        String pageString = json.getString("page");
        if (pageSizeString != null && countPageString != null && pageString != null) {
            countPage = Integer.parseInt(countPageString);
            if (countPage <=1) {
                pullToRefreshLayout.stopLoadMore();
            }
        }
    }


    private TextView textView;
    public void showPop() {
        mPopupWindow.showAtLocation((findViewById(R.id.public_txt_righe)), Gravity.TOP,0,0);
//        mPopupWindow.showAsDropDown((findViewById(R.id.public_txt_righe));
    }


    /**
     * 初始化 popupWindow 和 listview
     */
    private void initPopup() {
        mPopupWindow = new PopupWindow(this);
        View view = View.inflate(this, R.layout.activity_draw_view, null);
        int screenWidth = DensityUtil.getScreenHeight(AccountDetailsActivity.this);
        mPopupWindow.setHeight(screenWidth/2);
        mHomePopListviewLeft = (ListView) view.findViewById(R.id.home_pop_listview_left);
        mHomePopListviewRight = (ListView) view.findViewById(R.id.home_pop_listview_right);
        txt_btn_left = (ImageView)view.findViewById(R.id.txt_btn_left);
        txt_btn_left.setOnClickListener(this);
        txt_account_sure = (TextView)view.findViewById(R.id.txt_account_sure);
        txt_account_sure.setOnClickListener(this);
//        TextView mHomePopupTvAdviceLocation = (TextView) view.findViewById(R.id.home_popup_tv_advice_location);

//       将view添加到  popup里面
        mPopupWindow.setContentView(view);
        mPopupWindow.setBackgroundDrawable(new PaintDrawable());
        mPopupWindow.setFocusable(true);
//        mPopupWindow.setOutsideTouchable(true);

//        popupWindow消失的监听
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                F.id(public_txt_righe).text(getResources().getString(R.string.sx));
            }
        });

        //为了方便扩展，这里的两个ListView均使用BaseAdapter.如果分类名称只显示一个字符串，建议改为ArrayAdapter.
        //加载一级分类
        //加载左侧第一行对应右侧二级分类
        mFirstList = new ArrayList<>();
        mFirstList.add(getResources().getString(R.string.total));
        mFirstList.add(getResources().getString(R.string.yzn));
        mFirstList.add(getResources().getString(R.string.ygyn));
        mFirstList.add(getResources().getString(R.string.sgyn));
        mFirstList.add(getResources().getString(R.string.bnn));
        mFirstList.add(getResources().getString(R.string.ynn));

        final ListTimeAdapter firstAdapter = new ListTimeAdapter(this, mFirstList);
        mHomePopListviewLeft.setAdapter(firstAdapter);

        //加载左侧第一行对应右侧二级分类
        mSecondList = new ArrayList<>();
        mSecondList.add(getResources().getString(R.string.total));
        mSecondList.add(getResources().getString(R.string.cz));
        mSecondList.add(getResources().getString(R.string.access_account));
        mSecondList.add(getResources().getString(R.string.xdzf));
        mSecondList.add(getResources().getString(R.string.th_2));
        mSecondList.add(getResources().getString(R.string.qhqx));
        mSecondList.add(getResources().getString(R.string.zdkk));
        mSecondList.add(getResources().getString(R.string.bcj));
        mSecondList.add(getResources().getString(R.string.qxdg));
        mSecondList.add(getResources().getString(R.string.nghqx));
        mSecondList.add(getResources().getString(R.string.zjzhye));
        mSecondList.add(getResources().getString(R.string.jlzj));
        mSecondList.add(getResources().getString(R.string.fxzj));
        mSecondList.add(getResources().getString(R.string.ystq));

//
        final SecondClassAdapter secondAdapter = new SecondClassAdapter(this, mSecondList);
        mHomePopListviewRight.setAdapter(secondAdapter);

//        左侧ListView点击事件
        mHomePopListviewLeft.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Log.e("---------Left",position+"");
                firstAdapter.setSelectedPosition(position);
                firstAdapter.notifyDataSetChanged();
                str_time = position+"";

            }

        });

        //右侧ListView点击事件
        mHomePopListviewRight.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //关闭popupWindow，显示用户选择的分类
//                mPopupWindow.dismiss();

                Log.e("=========Right",position+"");
                secondAdapter.setSelectedPosition(position);
                secondAdapter.notifyDataSetChanged();
                if (position == 0){
                    str_billtype = "-1";//全部
                }else if (position == 1){
                    str_billtype = "0";//充值
                }else if (position == 2){
                    str_billtype = "1";//取现
                }else if (position == 3){
                    str_billtype = "4";//下单支付
                }else if (position == 4){
                    str_billtype = "5";//退货
                }else if (position == 5){
                    str_billtype = "6";//缺货取消
                }else if (position == 6){
                    str_billtype = "7";//自动扣款
                }else if (position == 7){
                    str_billtype = "8";//补差价
                }else if (position == 8){
                    str_billtype = "9";//取消订购
                }else if (position == 9){
                    str_billtype = "10";//NG货取消
                }else if (position == 10){
                    str_billtype = "12";//增加用户余额
                }else if (position == 11){
                    str_billtype = "13";//奖励资金
                }else if (position == 12){
                    str_billtype = "14";//返现资金
                }else if (position == 13){
                    str_billtype = "15";//遗失退钱
                }
            }
        });


    }

}

